package Servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.json.JSONObject;

import DAL.Entites.Rank;
import DAL.JDBC.DBConn;
import DAL.JDBC.RankJDBC;

public class GetRanksForGame extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public GetRanksForGame() {
        super();
    }


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		JSONObject result = new JSONObject();
		RankJDBC rankJDBC = new RankJDBC(DBConn.getConnection());
		
		int gameId = Integer.parseInt(request.getParameter("gameId"));
		
		List<Rank> ranks = rankJDBC.listRanksByGameId(gameId);
		try {
			result.put("ranks", ranks);
			result.put("average", calculateAverage(ranks));
		}
		catch (JSONException e) {
			e.printStackTrace();
		}
		
		PrintWriter pw = response.getWriter();
		pw.write(result.toString());
	}
	
	private double calculateAverage(List <Rank> marks) {
		  Integer sum = 0;
		  if(!marks.isEmpty()) {
		    for (Rank mark : marks) {
		        sum += mark.getRankNumber();
		    }
		    return sum.doubleValue() / marks.size();
		  }
		  return sum;
		}

}
